<template>
  <div class="the-page">
    <el-form ref="formRef" :rules="formRules" :model="upload.post" class="demo-form-inline" label-width="100px">
      <el-form-item label="用户" prop="customerId">
        <el-select v-model="upload.post.customerId" placeholder="请选择用户" style="width: 360px" filterable>
          <el-option v-for="item in props.customerList" :key="item.id" :label="`${item.id}-${item.name} (${item.phone})`" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="upload.post.title" show-word-limit maxlength="30" placeholder="输入标题"></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="upload.post.description" show-word-limit type="textarea" maxlength="1000" :rows="6" placeholder="输入内容描述"></el-input>
      </el-form-item>

      <el-form-item label="图片">
        <upload-aliyun-auth v-model:uploadStatus="upload.status" type="image" @image:success="uploadFn.successBack" @image:ready="uploadFn.readyBack" @clear="uploadFn.readyBack(0)" @image:progress="uploadFn.progressBack"></upload-aliyun-auth>
      </el-form-item>

      <el-form-item label="位置" prop="location">
        <span>请输入经度：</span>
        <el-input-number style="width:240px;margin: 0 8px 8px 0;" v-model="upload.post.longitude" placeholder="请输入经度" controls-position="right"></el-input-number>
        <span>请输入纬度：</span>
        <el-input-number style="width:240px;margin: 0 8px 8px 0;" v-model="upload.post.latitude" placeholder="请输入纬度" controls-position="right"></el-input-number>
        <el-input v-model="upload.post.location" placeholder="请输入位置地名"></el-input>
      </el-form-item>

      <el-form-item label="标签">
        <el-select v-model="upload.post.relatedTopic" multiple placeholder="请选择话题标签" style="width: 360px" filterable>
          <el-option v-for="item in props.tagsList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>


      <el-form-item style="text-align:center">
        <el-button type="primary" plain @click="uploadFn.submitPre(formRef)">提交</el-button>
      </el-form-item>
    </el-form>
    

    <el-dialog v-model="upload.isLoading" :close-on-click-modal="false" :show-close="false">
      <div v-for="(value,index) in upload.imagesProgress" :key="index" :style="{marginTop:index?'24px':''}">
        <span>图片#{{index+1}}#上传进度：</span>
        <el-progress :percentage="value" :color="[{ color: '#1989fa', percentage: 99 },{ color: '#67c23a', percentage: 100 }]" />
      </div>
 
    </el-dialog>
  </div>
</template>
<script setup>
import uploadAliyunAuth from "@/components/Upload/aliyunAuth";
import { ref, reactive, onMounted } from "vue";
import { uploadImageOrVideo,getTopicTagsList,getTestCustomerList } from "@/api/operation";
import { ElMessage } from 'element-plus';

const props = defineProps({
  customerList: {
    default: ()=>[],
    type: Object,
  },
  tagsList: {
    default: ()=>[],
    type: Object,
  },
})
const formRef = ref();
const formRules = reactive({
  customerId: [{ required: true, message: "请输入用户id", trigger: "blur" ,validator:(rule, value, callback) => {
    if (!value) {
      callback(new Error('请填写用户id！'))
    } else if (!/^\d+/.test(value)) {
      callback(new Error("请检查用户id格式！"))
    } else {
      callback()
    }
  }}],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
});

const { $data: upload, $fn: uploadFn } = (() => {
  const backup = {
    post:{
      type: "image",
      customerId: null,
      longitude: undefined,
      latitude: undefined,
      location: "",
      // musicId: "",
      title: "",//标题
      description: "",//描述
      coverImageId: "",//封面图id
      relatedTopic: "",
      image: [
        // {
        //   "imageId":"054216697db549ba8cda43021a2sebf1",
        //   "imageUrl":"/image/default/B0D8B642531C4DE586D646CC10850D1B-6-2.png",
        //   "width":500,
        //   "height":400
        // }
      ],
    }
  }
  const $data = reactive({
    isLoading: false,
    fileIsReady: false,//是否存在等在上传的文件，不存在则提示选择文件
    post:{...backup.post,image:[]},
    status:"",

    imagesProgress:[],
  });
  const $fn = {
    readyBack(num){
      $data.fileIsReady = !!num;
      if(num){
        $data.imagesProgress.length=num;
        $data.imagesProgress.fill(0);
      }
    },
    progressBack(value,index){
      $data.imagesProgress[index] = parseInt(value*100);
    },
    successBack(infos){
      console.log("successBack",infos)
      for(let info of infos){
        $data.post.image[info._index] = {
          imageId: info.imageId,
          imageUrl: info.imageUrl,
          width: info.width,
          height: info.height,
        }
      }
      $data.post.coverImageId = $data.post.image[0].imageId;
      $fn.submitData();
    },
    submitPre(formRef) {
      if (!formRef) return;
      formRef.validate((valid) => {
        if (valid) {
          if(!$data.fileIsReady){
            ElMessage.error("请选择文件！");
            return;
          }
          $data.isLoading = true;
          $data.status = "upload";
        }
      });
    },
    submitData() {
      // 数据验证
      let req = {
        ...$data.post,
        relatedTopic: (()=>{
          if(!$data.post.relatedTopic?.length){
            return "";
          }else{
            return $data.post.relatedTopic.join(",")
          }
        })(),
      };
      console.log("upload req:",req);
      // return;
      uploadImageOrVideo(req).then((res) => {
        if (res.code === 0) {
          console.log("upload res:",res);
          ElMessage.success("上传成功！");
          $data.status = "clear";
          $fn.resetPost();
        }
        $data.isLoading = false;
      });
    },
    resetPost(){
      $data.post = {...backup.post,image:[]};
      $data.post.image = [];
    },
  }
  return {
    $data,
    $fn,
  }
})();
</script>
<script>
export default {
  name: "uploadContent",
};
</script>

<style scoped lang="scss">
.the-page{
  background-color: #ffffff;
  padding: 12px;
}
</style>